<template>
	<checkbox-group :name="checkedField" @change="checkboxChange">
		<view style="display: flex; flex-flow:row wrap">
			<label v-for="(item,index) in list" :key="item[valueField]">
				<view class="tui-flex" style="padding-right: 5px;padding-top: 5px;">
					<view><checkbox :value="item[valueField] + ''" :checked="item.checked" 
					class='green' :disabled="item.disabled" :class="item.checked?'checked':''"/></view>
					<view>{{ item[nameField]}}</view>
				</view>
			</label>
		</view>
	</checkbox-group>
</template>

<script>
	export default {
		inject: ['form'],
		props:{
			list:{
				type:Array,
				default() {
					return []
				}
			},
			checkedField:{
				type: String,
				default() {
					return 'checkList'
				}
			},
			valueField:{
				type: String,
				default() {
					return 'id'
				}
			},
			nameField:{
				type: String,
				default() {
					return 'name'
				}
			},
			formValueField:{
				type: String,
				default() {
					return ''
				}
			},
			formNameField:{
				type: String,
				default() {
					return ''
				}
			}
			
		},
		created() {
			for(let item of this.list){
				if(item.attr.checked === true){
					item.checked = true
				}
			}
		},
		watch:{
			list:{
				handler(newVla,oldVal){
					let checkList = [],
						ids = [],
						names=[]
					for(let item of this.list){
						if(item.attr.checked === true){
							item.checked = true
							ids.push(item[this.valueField])
							names.push(item[this.nameField]) 
							checkList.push(item);
						}
						if(item.attr.disabled == true){
							item.disabled = true
						}
					}
					this.insertArr(ids,names,checkList)
				}
			}
		},
		methods: {
			checkboxChange: function(e) {
				let items = this.list,
					values = e.detail.value,
				    checkList = [],
					ids = [],
					names=[]
				for (let i = 0, lenI = items.length; i < lenI; ++i) {
					let item = items[i];
					if (values.includes(item[this.valueField].toString())) {
						this.$set(item, 'checked', true);
						this.$set(item.attr, 'checked', true);
						ids.push(item[this.valueField])
						names.push(item[this.nameField]) 
						checkList.push(item);
					} else {
						this.$set(item, 'checked', false);
						this.$set(item.attr, 'checked', false);
					}
				}
				this.insertArr(ids,names,checkList)
				this.$emit('checkboxChange',e)
			},
			insertArr(ids=[],names=[],checkList=[]){
				if(this.form.formdata){
					if(this.formValueField){
						this.form.formdata[this.formValueField] = ids.join(",")
					}
					if(this.formNameField){
						this.form.formdata[this.formNameField] = names.join(",")
					}
				}else{
					if(this.formValueField){
						this.form[this.formValueField] = ids.join(",")
					}
					if(this.formNameField){
						this.form[this.formNameField] = names.join(",")
					}
				}
				this.$forceUpdate()
				this.$emit("change", checkList)
			},
		}
	}
</script>
